#!/user/bin/env python
# -*- coding: utf-8 -*-
''' 
Author: Sjy
Description: 显示后处理场
'''

__all__= []

import json
from PyQt5 import QtCore, QtGui, QtWidgets  

from gui.controls import envs
from gui.controls import apis 
from gui.components import ui_custom_form as UIForm
from gui.components import message_box as MBox

import gui.controls.globalvar as GL

global CACHE 
CACHE = {}

global DIALOG   
DIALOG = None
class DlgShowThreshold(QtWidgets.QDialog):
    def __init__(self, parent=None):
        global DIALOG 
        if DIALOG:return  # 判断对话框是否已经存在存在则退出
        DIALOG = self

        parent = parent or GL.get_value("py3d")
        super(DlgShowThreshold, self).__init__(parent)
        self.initUI()
        self.setWindowTitle("显示结果")
        self.show()
        # 注册对话框关闭事件
        self.finished.connect(self.__on_finished)
        
    def initUI(self):
        self.__ui = UIForm.UiCustomForm(self.__get_ui_config())
        self.__ui._setup_ui(self)
        flag = CACHE.get("flag") or ""
        modelFile = CACHE.get("modelFile") or ""
        self.__ui._sets({
            "flag":flag,
            "modelFile":modelFile,
        })
        self.__on_changed_flag(flag)
        self.__ui._sets({
            "name":CACHE.get("name") or "",
        })

    def __get_ui_config(self) -> json:
        return {
            # "icon": "icon.png", # window icon
            # "objectName": "test", # window objectName
            "layout":{ # window 主布局
                "margin": [10, 10, 10, 10], # window 主布局的margin
                "space": 10,  # window 主布局的 Space
                # "objectName": "qLayout", # window 主布局的 objectName
            },
            "items":[
                {
                    "type": "file",
                    "key":"modelFile",
                    "typeParams": { # 不同的类型所需要的参数不同，由typeParams来传递
                        "title": "打开模型",
                        "fileType": "VTU Files (*.vtu);;VTK Files (*.vtk)",
                        "readOnly": False,
                        "onSelected":lambda file, *args, **kwargs: self.__on_selected_file(file)
                    },
                    "styleParams":{ # 控制样式的参数
                        "margin": [0, 0, 0, 0],
                        "space": 10,
                        "labWidth": 100,
                        "minWidth": 400,
                    },
                },
                {
                    "type": "separator",
                    "styleParams":{ # 控制样式的参数
                        "margin": [0, 0, 0, 0],
                    }
                },
                {
                    "type": "radios",
                    "key":"flag",
                    "title": "类型",
                    "styleParams":{ # 控制样式的参数
                        "labWidth": 100,
                        "margin": [0, 0, 0, 0],
                        "space": 10,
                        "minWidth": 400,
                    },
                    "typeParams": { # 不同的类型所需要的参数不同，由typeParams来传递
                        "data": [
                            {"title": "单元", "value": "cell"},
                            {"title": "节点", "value": "point"},
                        ],
                        "onChanged": lambda value: self.__on_changed_flag(value) 
                    }   
                },
                {
                    "type": "select",
                    "key":"name",
                    "title": "场",
                    "styleParams":{ # 控制样式的参数
                        "margin": [0, 0, 0, 0],
                        "space": 10,
                        "minWidth": 400,
                        "labWidth": 100,
                    },
                    "typeParams": { # 不同的类型所需要的参数不同，由typeParams来传递
                        "data": [], # 动态获取
                        "hasDefaultOption":True, # 设置存在默认选项
                    },
                    "onLayoutAppendWidget":lambda layout: self.__append_refresh_btn(layout)
                },
                # {
                #     "type": "checkbox",
                #     "key":"hideLine",
                #     "title": "隐藏线",
                #     "styleParams":{ # 控制样式的参数
                #         "margin": [0, 0, 0, 0],
                #         "space": 10,
                #         "minWidth": 400,
                #         "labWidth": 100,
                #     },
                #     "typeParams": { # 不同的类型所需要的参数不同，由typeParams来传递
                #     },
                #     "onLayoutAppendWidget":lambda layout: self.__append_refresh_btn(layout)
                # },
                {},
                {
                    "type": "tools",
                    "typeParams": { # 不同的类型所需要的参数不同，由typeParams来传递
                        "items": [
                            
                            {
                                "title": "恢复",
                                "action":lambda: self.__on_recover(),
                            },
                            {
                                "title": "关闭",
                                "action":lambda: self.reject(),
                            }
                        ],
                    },
                    "styleParams":{ # 控制样式的参数
                        "margin": [0, 0, 0, 0],
                        "space": 10,
                    }
                },
            ]
        }
    
    def __on_selected_file(self, file:str=None) -> None:
        """选择模型文件之后的回调
        Args:
            file (str, optional): 文件选择. Defaults to None.
        """
        # 判断是 vtk 还是 vtu
        vtu = file.lower().endswith(".vtu")
        if vtu:
            apis.open_vtu(file)
        else:
            apis.open_vtk(file)
        self.__on_changed_flag()
        self.__ui._sets({
            "name": "",
            "flag": ""
        })

        self.set_cache("modelFile", file)
        self.set_cache("name", "")
        self.set_cache("flag", "")

    def _set_file(self, file:str="") -> None:
        """设置数据
        Args:
            data (dict, optional): _description_. Defaults to {}.
        """
        self.__ui._sets({
            "modelFile": file,
        })
        self.set_cache("modelFile", file)
        



    def __append_refresh_btn(self, layout:QtWidgets.QHBoxLayout=None) -> None:
        """初始化场名称name所在行的组件 因为需要追加一个刷新按钮
        Args:
            widget (QtWidgets.QWidget, optional): _description_. Defaults to None.
        """
        btn = QtWidgets.QPushButton("刷新")
        # 设置btn 仅适应内容宽度
        btn.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum , QtWidgets.QSizePolicy.Fixed))
        btn.clicked.connect(self.__on_refresh)
        layout.addWidget(btn)

        # btn = QtWidgets.QPushButton("隐藏线")
        # # 设置btn 仅适应内容宽度
        # btn.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum , QtWidgets.QSizePolicy.Fixed))
        # btn.clicked.connect(self.__on_hide_line)
        # layout.addWidget(btn)

    def __on_refresh(self) -> None:
        """刷新场列表
        """
        info = self.__ui._gets() or {}
        data = info.get("data") or {}
        flag = data.get("flag") or ""
        name = data.get("name") or ""
        if not flag :return MBox.warning("请先选择场的类型")
        if not name :return MBox.warning("请先选择场名")

        self.set_cache("name", name)
        self.set_cache("flag", flag)

        print("flag ", flag)
        print("name ", name)
        apis.show_color_range(name, flag)

    # def __on_hide_line(self) -> None:
    #     """隐藏线
    #     """
    #     apis.Theme().setThemEnableLine(False)
        
    def __on_changed_flag(self, flag:str="") -> None:
        """切换单元集合和节点集合
        Args:
            value (str, optional): _description_. Defaults to "".
        """
        # 要更新 场列表显示的内容
        widget = self.__ui._get_widget("name")
        if hasattr(widget, "_set_items"):
            names = []
            if flag == "cell":
                names = apis.get_cell_names()
            elif flag == "point":
                names =apis.get_point_names()
            widget._set_items(names)

    def __on_recover(self) -> None:
        """恢复场
        """
        global CACHE
        file = CACHE.get("modelFile") or ""
        if file:
            vtu = file.lower().endswith(".vtu")
            if vtu:
                apis.open_vtu(file)
            else:
                apis.open_vtk(file)
        

        self.set_cache("name", "")
        self.set_cache("flag", "")

    def set_cache(self, key, value):
        """设置缓存
        Args:
            data (dict, optional): _description_. Defaults to {}.
        """
        global CACHE
        CACHE[key] = value

        GL.set_value(f"threshold.{key}", value)

    def __on_finished(self, *args, **kwargs):
        global DIALOG
        DIALOG = None

